import ProForm, {
  ModalForm,
  ProFormGroup,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { message } from 'antd';
import React, { useRef } from 'react';

type FormProps = {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: number[]) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, onCancel, onSubmit } = props;
  if (!visible) {
    return <></>;
  }

  // const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const handleFormSubmit = async () => {
    let inst: string | undefined = formRef.current?.getFieldValue('inst');
    if (!inst) {
      message.error('请输入实例ID');
      return;
    }
    let instList = inst.split('\r\n');
    if (instList.length == 0) {
      message.error('请输入实例ID');
      return;
    }
    let ids: number[] = [];
    for (let i = 0; i < instList.length; i++) {
      let num = parseInt(instList[i]);
      if (isNaN(num)) {
        message.error('包含无效实例ID');
        return;
      }
      ids.push(num);
    }

    onSubmit(ids);
  };

  return (
    <ModalForm<{
      table: API.VpnServerBatchModel[];
    }>
      width={1000}
      open={visible}
      title="批量删除服务器"
      onFinish={handleFormSubmit}
      modalProps={{
        onCancel: onCancel,
        //destroyOnClose: false,
        maskClosable: false,
      }}
      // submitter={{

      // }}
    >
      <ProForm<API.VpnServerBatchModel>
        formRef={formRef}
        layout="horizontal"
        style={{
          margin: 'auto',
          marginTop: 0,
          marginLeft: 25,
          width: 1400,
          height: 600,
        }}
        submitter={{
          render: (props, doms) => {
            return [];
          },
        }}
        onFinish={handleFormSubmit}
      >
        <ProFormGroup>
          <ProFormTextArea
            name="inst"
            label="服务器实例ID (一行一个实例ID)"
            width={800}
            fieldProps={{ rows: 25 }}
          />
        </ProFormGroup>
      </ProForm>
    </ModalForm>
  );
};

export default Form;
